/*
 * Copyright By ZATI
 * Copyright By 3a3c88295d37870dfd3b25056092d1a9209824b256c341f2cdc296437f671617
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package cn.wzc.crystal.platform.logic.impl;

import cn.wzc.crystal.platform.logic.Logic;
import cn.wzc.crystal.platform.logic.LogicChain;
import cn.wzc.crystal.platform.logic.LogicRegister;
import cn.wzc.crystal.platform.logic.LogicRepository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MemoryLogicRepository implements LogicRepository, LogicRegister {

	private final Map<String, Map<String, Logic>> logicStore = new ConcurrentHashMap<>();

	@Override
	public Logic registerLogic(String group, String name, Logic logic) {
		Map<String, Logic> logics = getGroup(group);
		logics.put(name, logic);
		return logic;
	}

	@Override
	public Logic unRegisterLogic(String group, String name) {
		Map<String, Logic> logics = getGroup(group);
		return logics.remove(name);
	}

	@Override
	public LogicChain getLogic(String group) {
		Collection<Logic> logicCollection = getGroup(group).values();
		return new LogicChain(logicCollection);
	}

	private Map<String, Logic> initGroup(String s) {
		return new HashMap<>();
	}

	private Map<String, Logic> getGroup(String group) {
		return logicStore.computeIfAbsent(group, this::initGroup);
	}
}
